package ThreadPool;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/**
 * 读写锁
 * 模拟读写分离
 * 不加锁的话，可能在写的过程中导致还没有写结束就被cpu抢去执行权去读，所以需要加锁
 * **/
public class ThreadWriteReadLock {

    private  static volatile Map<String,Object> map = new HashMap<String, Object>();
    static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    static Lock r = rwl.readLock();
    static Lock w = rwl.writeLock();

    public static Object put(String key, Object value){
        w.lock();
        try{
            System.out.println("正在做写的操作,key:" + key + ",value:" + value + "开始.");
            Thread.sleep(100);
            System.out.println("正在做写的操作,key:" + key + ",value:" + value + "结束.");
            Object object = map.put(key,value);
            return object;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            w.unlock();
        }
        return null;
    }

    public  static  Object get(String key){
        r.lock();
        try{
            System.out.println("正在做读的操作,key:" + key + "" + "开始.");
            Thread.sleep(100);
            Object object = map.get(key);
            System.out.println("正在做读的操作,key:" + key + ",value:" +object + "结束.");
            return  object;
        }catch (Exception e){

        }finally {
            r.unlock();
        }
        return null;
    }

    public static void main(String[] args) {
        new Thread(new Runnable() {


            public void run() {
                for (int i = 0; i < 10; i++) {
                    ThreadWriteReadLock.put(i + "", i + "");
                }

            }
        }).start();
        new Thread(new Runnable() {


            public void run() {
                for (int i = 0; i < 10; i++) {
                    ThreadWriteReadLock.get(i + "");
                }

            }
        }).start();

    }
}


